/**
 * 按统一格式显示表单，方便维护，不设置相关操作参数信息，即不显示相关按钮，removeParams=null，即工具栏不显示删除按钮
 * @param {Object} datagridId 数据集对应table的id
 * @param {Object} listUrl 请求数据集的action
 * @param {Object} title 数据集的标题
 * @param {Object} columns 数据集的列信息
 * @param {Object} editParams 编辑操作（新增和编辑）参数
 * @param {Object} addParams 新增操作参数
 * @param {Object} removeParams 删除操作参数
 * @param {Object} modifyParams 修改操作参数
 * @param {Object} queryParams 查询操作参数
 * @param {Object} exportParams 导出操作参数
 */
function showDataGrid(datagridId, listUrl, title, columns, editParams, addParams, removeParams, queryParams, modifyParams, exportParams){
    // 给查询按钮绑定点击事件，更新datagrid中数据
    if (queryParams !=
    null) {
        var queryBtnId = queryParams.queryBtnId;
        
        $("#" + queryBtnId).click(function(){
            var params = "{";
            // 从查询表单中获取所有的非button、submit、reset的input控件的键值，并拼接成json格式的字符串
            var inputs = $(":input", $("#" + queryParams.queryFormId));
            for (var i = 0; i < inputs.size(); i++) {
                if ($(inputs[i]).attr("type") != "button" && $(inputs[i]).attr("type") != "submit" && $(inputs[i]).attr("type") != "reset") {
                    if ($(inputs[i]).attr("id") != undefined) {
                        params += "'" + $(inputs[i]).attr("id") + "':'" + $(inputs[i]).val() + "'" + ",";
                    }
                }
            }
            params = params.substr(0, params.length - 1) + "}";
            
            // 根据查询参数更新datagrid
            $('#' + datagridId).datagrid({
                pageNumber: 1,
                queryParams: eval("(" + params + ")")
            });
        });
    }
    
    // 判断是否显示checkbox，如果不存在编辑和删除按钮，则不显示
    var showCheckbox = "";
    if ((editParams ==
    null ||
    modifyParams ==
    null) &&
    removeParams ==
    null) {
        showCheckbox = [[]];
    }
    else {
        showCheckbox = [[{
            field: 'ck',
            checkbox: true
        }]];
    }
    
    // 显示工具栏
    var addSplit = false;
    var toolbar = "[";
    // 新增按钮
    if ((editParams !=
    null &&
    addParams !=
    null)) {
        var winId = editParams.modalWinId;
        var submitBtnId = editParams.submitBtnId;
        var formId = editParams.formId;
        var msgFlag = editParams.msgFlag;
        toolbar += "{text: '新增',iconCls: 'icon-add',handler: function(){add('" + datagridId + "', '" + winId + "', '" + submitBtnId + "', '" + formId + "', '" + addParams.addUrl + "', '" + msgFlag + "'); }}";
        addSplit = true;
    }
    else {
        addSplit = false;
    }
    if (addSplit) {
        toolbar += ",'-'";
    }
    // 编辑按钮
    if ((editParams !=
    null &&
    modifyParams !=
    null)) {
        var winId = editParams.modalWinId;
        var submitBtnId = editParams.submitBtnId;
        var formId = editParams.formId;
        var msgFlag = editParams.msgFlag;
        var loadUrl = modifyParams.loadUrl;
        var identityId = modifyParams.identityId;
        toolbar += (addSplit ? "," : "") + "{text: '修改',iconCls: 'icon-edit',handler: function(){modify('" + datagridId + "', '" + winId + "', '" + submitBtnId + "', '" + formId + "', '" + loadUrl + "', '" + identityId + "', '" + modifyParams.modifyUrl + "', '" + msgFlag + "'); }}";
        addSplit = true;
    }
    else {
        addSplit = false;
    }
    if (addSplit) {
        toolbar += ",'-'";
    }
    // 删除按钮
    if (removeParams !=
    null) {
        var identityId = removeParams.identityId;
        var removeUrl = removeParams.removeUrl;
        var msgFlag = removeParams.msgFlag;
        toolbar += (addSplit ? "," : "") + "{text: '删除',iconCls: 'icon-remove',handler: function(){removeRow('" + datagridId + "', '" + identityId + "', '" + removeUrl + "', '" + msgFlag + "'); }}";
        addSplit = true;
    }
    else {
        addSplit = false;
    }
    if (addSplit) {
        toolbar += ",'-'";
    }
    // 导出按钮
    if (exportParams !=
    null) {
        var exportUrl = exportParams.exportUrl;
        toolbar += (addSplit ? "," : "") + "{text: '导出',iconCls: 'icon-save',handler: function(){exportRows('" + exportUrl + "'); }}";
        addSplit = true;
    }
    else {
        addSplit = false;
    }
    if (addSplit) {
        toolbar += ",'-'";
    }
    toolbar += "]";
    
    // 是否设置工具栏
    if (toolbar != "[]") {
        $('#' + datagridId).datagrid({
            url: listUrl,
            title: title,
            rownumbers: true,
            pagination: true,
            singleSelect: true,
            pageSize: 10,
            pageList: [5, 10, 15, 20],
            fitColumns: true,
            striped: true,
            nowrap: false,
            frozenColumns: showCheckbox,
            columns: columns,
            toolbar: eval("(" + toolbar + ")")
        });
    }
    else {
        $('#' + datagridId).datagrid({
            url: listUrl,
            title: title,
            rownumbers: true,
            pagination: true,
            singleSelect: true,
            pageSize: 10,
            pageList: [5, 10, 15, 20],
            fitColumns: true,
            striped: true,
            nowrap: false,
            frozenColumns: showCheckbox,
            columns: columns
        });
    }
}

/**
 * 新增记录 修改返回data.msg，action中必须指定msg属性
 * @param {Object} datagridId datagrid Id
 * @param {Object} addOrEditWinId window窗口id
 * @param {Object} addOrEditBtnId form表单的ok按钮id
 * @param {Object} formId form表单
 * @param {Object} addUrl 新增记录的请求action
 * @param {Object} msg 返回消息的标识
 */
function add(datagridId, addOrEditWinId, addOrEditBtnId, formId, addUrl, msg){
    var datagrid = $('#' + datagridId);
    
    $('#' + addOrEditWinId).window({
        title: "新增",
        iconCls: "icon-add"
    });
    $('#' + addOrEditBtnId).linkbutton({
        iconCls: 'icon-ok',
        text: "添加"
    });
    
    $('#' + addOrEditWinId).window('open');
    $('#' + formId).show();
    $('#' + formId).form('clear');
    
    // 同一个按钮(新增和修改)，先解除方法绑定，再指定新增方法
    $("#" + addOrEditBtnId).unbind("click");
    $("#" + addOrEditBtnId).click(function(){
    
        // 表单验证及提交
        if (!$('#' + formId).form('validate')) {
            return false;
        }
        var params = "time=" + new Date();
        inputs = $(":input", $("#" + formId));
        for (var i = 0; i < inputs.size(); i++) {
            if (inputs[i].id) {
                params += "&" + inputs[i].id + "=" + $(inputs + "[name='" + inputs[i].id + "']", '#' + formId).val();
            }
        }
        
        $.ajax({
            type: "POST",
            url: addUrl,
            data: params,
            dataType: "json",
            success: function callback(data){
                if (msg.trim().length > 0) 
                    $.messager.alert('提示', data[msg], 'info');
                $('#' + addOrEditWinId).window('close');
                datagrid.datagrid('reload');
            }
        });
    });
}

/**
 * 修改记录 修改返回data.msg，action中必须指定msg属性
 * @param {Object} datagridId 待删除记录的datagrid Id
 * @param {Object} addOrEditWinId window窗口id
 * @param {Object} addOrEditBtnId window按钮id
 * @param {Object} formId window窗口中的form表单id
 * @param {Object} updateUrl 更新地址url
 * @param {Object} msg 返回消息的标识
 */
function modify(datagridId, addOrEditWinId, addOrEditBtnId, formId, loadUrl, identityId, updateUrl, msg){

    var datagrid = $('#' + datagridId);
    var selected = datagrid.datagrid('getSelected');
    if (selected) {
        // 修改window窗口的信息
        $('#' + addOrEditWinId).window({
            title: "修改",
            iconCls: "icon-edit"
        });
        $('#' + addOrEditBtnId).linkbutton({
            iconCls: 'icon-ok',
            text: "修改"
        });
        
        // 显示包含表单的window窗口
        $('#' + addOrEditWinId).window('open');
        $('#' + formId).show();
        $('#' + formId).form('clear');
        
        // 将数据填充到表单中，级联时需页面加载完成后触发
        /**
         * 级联下拉列表，数据填充，html标签上定义属性higherCascadeId和comboboxUrl，higherCascadeId的值为上一级的id
         * higherCascadeId="bureauId"
         * comboboxUrl="../archives/showStationsBelonged.action"
         */
        inputs = $(":input", $("#" + formId));
        $('#' + formId).form({
            onLoadSuccess: function(){
                for (var i = 0; i < inputs.size(); i++) {
                    if (inputs[i].id != "" && inputs[i].id != null && inputs[i].id != undefined) {
                        var $input = $("#" + inputs[i].id, '#' + formId);
                        if ($input.hasClass("easyui-combobox")) {
                            if ($input.attr("higherCascadeId") != "" && $input.attr("higherCascadeId") != undefined && $input.attr("higherCascadeId") != null) {
                                higherCascadeId = $input.attr("higherCascadeId");
                                var value = $(inputs + "[name='" + higherCascadeId + "']", '#' + formId).val();
                                var url = $input.attr("comboboxUrl");
                                var index = url.indexOf("?");
                                if (index == -1) {
                                    url += "?" + $input.attr("higherCascadeId") + "=" + value;
                                }
                                else {
                                    paramIndex = url.indexOf(higherCascadeId);
                                    if (paramIndex == -1) 
                                        url = url + "&" + $input.attr("higherCascadeId") + "=" + value;
                                    else 
                                        url = url.substr(0, paramIndex + higherCascadeId.length + 1) + value;
                                }
                                $input.combobox('reload', url);
                            }
                        }
                    }
                }
            }
        });
        // (拼接参数；请求url填充form)
        var params = "time=" + new Date();
        identityId = identityId.split(",");
        for (var i = 0; i < identityId.length; i++) {
            params += "&" + identityId[i] + "=" + selected[identityId[i]];
        }
        $('#' + formId).form('load', loadUrl + "?" + params);
        
        
        // 同一个按钮(新增和修改)，先解除方法绑定，再指定修改方法
        $("#" + addOrEditBtnId).unbind("click")
        $("#" + addOrEditBtnId).click(function(){
        
            // 表单验证及提交
            if (!$('#' + formId).form('validate')) {
                return false;
            }
            var params = "time=" + new Date();
            for (var i = 0; i < inputs.size(); i++) {
                if (inputs[i].id) {
                    params += "&" + inputs[i].id + "=" + $(inputs + "[name='" + inputs[i].id + "']", '#' + formId).val();
                }
            }
            $.ajax({
                type: "POST",
                url: updateUrl,
                data: params,
                dataType: "json",
                success: function callback(data){
                    if (msg.trim().length > 0) 
                        $.messager.alert('提示', data[msg], 'info');
                    $('#' + addOrEditWinId).window('close');
                    datagrid.datagrid('reload');
                }
            });
        });
    }
    else {
        $.messager.alert('提示', '请选择一行数据...', 'warning');
    }
}

/** 删除datagrid中行记录
 *
 * @param {Object} datagridId 待删除记录的datagrid Id
 * @param {Object} deleteUrl 删除记录的请求地址
 * @param {Object} rowId 删除记录的主键
 * @param {Object} msg 返回消息的标识
 */
function removeRow(datagridId, rowId, deleteUrl, msg){
    var datagrid = $('#' + datagridId);
    var selected = datagrid.datagrid('getSelected');
    if (selected) {
        $.messager.confirm('提示', '确认删除么?', function(status){
            if (status) {
                var rowIdVal = selected[rowId];
                $.ajax({
                    type: "POST",
                    url: deleteUrl,
                    data: rowId + "=" + rowIdVal,
                    dataType: "json",
                    success: function callback(data){
                        if (msg.trim().length > 0) 
                            $.messager.alert('提示', data[msg], 'info');
                        datagrid.datagrid('reload');
                    }
                });
            }
        });
    }
    else {
        $.messager.alert('提示', '请选择一行数据...', 'warning');
    }
}

/**
 * 导出Excel
 * @param {Object} exportUrl 导出Excel的url
 */
function exportRows(exportUrl){

    window.location.href = exportUrl;
}

/**
 * 关闭window窗口
 * @param {Object} winId window窗口的id
 */
function winClose(winId){

    $('#' + winId).window('close');
}

/**
 * 百分比宽度
 * @param {Object} percent
 */
function fixWidth(percent){
    return document.body.clientWidth * percent;
}
